package com.xxx.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ZooKeeperService {

    @Autowired
    private CuratorFramework curatorFramework;

    // 创建zk节点
    public void createNode(String path, String data) throws Exception {
        curatorFramework.create()
                .creatingParentsIfNeeded()  // 如果父节点不存在，自动创建
                .withMode(CreateMode.PERSISTENT)  // 持久化节点
                .forPath(path, data.getBytes());
    }

    // 修改zk节点
    public void updateNode(String path, String data) throws Exception {
        curatorFramework.setData()
                .forPath(path, data.getBytes());
    }

    // 读取zk节点数据
    public String getNodeData(String path) throws Exception {
        byte[] data = curatorFramework.getData().forPath(path);
        return new String(data);
    }

    // 监听zk节点变化
    public void watchNode(String path) throws Exception {
        NodeCache nodeCache = new NodeCache(curatorFramework, path);
        nodeCache.getListenable().addListener(() -> {
            byte[] data = nodeCache.getCurrentData().getData();
            log.info("监听到节点：{} 数据变化：{}", path, new String(data));
        });
        nodeCache.start();
    }

    // 获取zk分布式锁对象
    public InterProcessMutex getDistributeLock(String path) throws Exception {
        // 声明锁对象，本质是zk临时有序节点
        InterProcessMutex mutex = new InterProcessMutex(curatorFramework, path);
        return mutex;
    }

}